/*
**    Copyright (C) 2003-2010 Institute for Systems Biology
**                            Seattle, Washington, USA.
**
**    This library is free software; you can redistribute it and/or
**    modify it under the terms of the GNU Lesser General Public
**    License as published by the Free Software Foundation; either
**    version 2.1 of the License, or (at your option) any later version.
**
**    This library is distributed in the hope that it will be useful,
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
**    Lesser General Public License for more details.
**
**    You should have received a copy of the GNU Lesser General Public
**    License along with this library; if not, write to the Free Software
**    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*/

package org.systemsbiology.ml;

import org.systemsbiology.util.Clicker;
import org.systemsbiology.util.KahanSummation;
import org.systemsbiology.util.Pair;

import java.util.HashMap;

import static java.lang.Math.log;

/**
 * This class defines a Summator that computes the Shannon mutual information between two values.
 *  This is, of course, the generalization of {@link ShannonSummation} for two values instead of one.
 * @author trobinso
 */
public class MutualInformation<L,R> {


    KahanSummation wrapped = new KahanSummation();  // Uses Kahan Summation to guarantee a memory footprint of O(1) WRT
                                                    //  the input data set while minimizing roundoff error.

    HashMap<L,Integer> ell = new HashMap<L,Integer>();
    HashMap<R,Integer> arr = new HashMap<R,Integer>();

    public MutualInformation(Clicker<Pair<L,R>> given) {
        if (given == null) {
            throw new IllegalArgumentException("given Clicker<Pair<L,R>> cannot be null");
        }

        // Construct the values for each individual event
        for(Pair<Pair<L,R>, Integer> keyvalue: given) {
            
            int left = 0;
            if (ell.containsKey(keyvalue.first.first)) {
                left += ell.get(keyvalue.first.first);
            }
            ell.put(keyvalue.first.first, left + keyvalue.second);
            
            int right = 0;
            if (arr.containsKey(keyvalue.first.second)) {
                right += arr.get(keyvalue.first.second);
            }
            arr.put(keyvalue.first.second, right + keyvalue.second);
        }

        // Iterate back through the Clicker, extracting the individual probabilities as needed
        double total = (double)given.total();
        for(Pair<Pair<L,R>, Integer> keyvalue: given) {
            double prob = (keyvalue.second / total);
            wrapped.add(prob *
                    log(prob / (ell.get(keyvalue.first.first) * arr.get(keyvalue.first.second)))/log(2));
        }
    }

    public double total() {
        return wrapped.total();
    }    
}
